Python API Reference

This chapter provides information on eCognition's python API with reference for each class, properties, and methods and gives hints on printing and the usage of external python files in inline scripts. Exemplary python scripts can be found in User Guide > Python Integration.

How to set up and use an external debugger for python files see User Guide > Python Integration > Debugging python code in eCognition Developer

 

For more information see also:

Installation Guide > Windows > Python Installation - installation and setup

Reference Book > Algorithms and Processes > Miscellaneous > Python Script - description algorithm and its parameters

User Guide > Python Integration - application examples for python scripts and Debugging python code in eCognition Developer

Module eCognition

eCognition's algorithm 'python script' calls a specified python function with a single function argument of type dict, that contains all of the selected algorithm parameters.


Function argument structure:

{

    "scene_info": {

        "LLX": float,

        "LLY": float

        "resolution": float,

        "projection_string": str,

        "unit": str

    },

    "raster": {

        "name1": ecognition.Raster,

        "name2": ecognition.Raster,

        ...

    },

    "vector": {

        "name1": ecognition.Vector,

        "name2": ecognition.Vector,

        ...

    },

    "point_cloud": {

        "name1": ecognition.PointCloud,

        "name2": ecognition.PointCloud,

        ...

    },

    "variable" : {

        "name1": str | float,

        "name2": str | float,

        ...

    },

    "region" : {

        "name1": numpy.ndarray (check set_region function for region explanation),

        "name2": numpy.ndarray (check set_region function for region explanation),

        ...

    },

    "array" : {

        "name1": list[str | float],

        "name2": list[str | float],

        ...

    }

}


Here “name*” will be equal to the name of the selected variable or layer in the “execute python script” process dialog.

class Raster

Available methods:

read_data(x=0, y=0, sx=0, sy=0)

Reads data from the raster image object. Can be called multiple times, to allow reading data in chunks for large rasters.

Parameters:

x: int

X data read starting location.

y: int

Y data read starting location.

sx: int

X data read size. If sx is equal to 0, then full size is read.

sy: int

Y data read size. If sy is equal to 0, then full size is read.

Returns:

data: numpy.ndarray

The read data in the shape of [sy, sx].

Raises:

ValueError

if any of the arguments is negative, or either of x and y are bigger than scene size.

write_data(data, x_offset=0, y_offset=0)

Writes data to the raster image object. Can be called multiple times, to allow writing data in chunks for large rasters.

Parameters:

data: numpy.ndarray

The data to write into the raster. Must be of the same data type as a raster object. Must be a 2D Y-major array (y, x).

x_offset: int

X data write starting location.

y_offset: int

Y data write starting location.

Raises:

ValueError

If Raster is already closed, data type is mismatched, or out of bounds.

size()

Returns the size of the raster image.

Returns:

raster_size: tuple

This tuple will have 2 dimensions and looks like this: (y_size, x_size).



get_datatype()

Returns the data type of the raster image.

Returns:

raster_datatype: numpy.dtype

data of the raster image as numpy dtype.


close()

Finalizes raster object. Must be called for new raster objects created with ecognition.Raster.create_raster method.

Raises:

ValueError

When closing an already closed raster.


Available static methods:

create_raster(name, type)

Static method

Creates an empty raster with the given name and type. If the raster with the specified name already exists, it is deleted, before a new one is created.

Parameters:

name: str

Name of the raster.

type: numpy.dtype

Data type of the raster values.

Returns:

raster: ecognition.Raster

The created raster.

Raises:

ValueError

If type is unsupported.

create_raster(name, data)

Static method

Creates a raster from the given data, with the given name. Data type is the same as data.dtype. If the raster with the specified name already exists, it is deleted, before a new one is created.

Parameters:

name: str

Name of the raster.

data: numpy.ndarray

Data to fill the raster with.

Returns:

raster: ecognition.Raster

The created raster.

Raises:

ValueError

If type is unsupported, or out of bounds

class Vector

Available methods:

get_geometry_type()

Returns the type of the vector geometry.

Returns:

geometry_type: str

The string indicating geometry type. Can be one of [“Point”, “Line”, “Polygon”, “Point3D”, “Line3D”, “Polygon3D”].

get_data()

Returns data of the vector as a pandas DataFrame. Geometries are located in the “geometry” column. Other attributes are contained in other columns. Geometries are objects from the shapely.geometry module.

Returns:

vector_data: pandas.DataFrame

Vector data as pandas DataFrame.

close()

Finalizes the vector object. Must be called for new vector objects created with ecognition.Vector.create_vector method.


Available static methods:

create_vector(name, geometry_type, data)

Static method

Creates a vector from the given data, with the given name. If the vector with the specified name already exists, it is deleted, before a new one is created. pandas DataFrame given in the data argument must contain a “geometry” column, with at least one geometry. The elements of each DataFrame column must have the same type.

Parameters:

name: str

Name of the vector.

geometry_type: str

Type of the geometries. Must be one of [“Point”, “Line”, “Polygon”, “Point3D”, “Line3D”, “Polygon3D”].

data: pandas.DataFrame

The data to fill the vector with.

Returns:

vector: ecognition.Vector

The created vector.

Raises:

ValueError

If the geometry type is unsupported, pandas DataFrame does not contain a geometry column or is empty.

If the name is empty.

If attribute type is unsupported, or attribute elements are not of the same type.

class PointCloudChunk

Available attributes:

x

Read-only property

Returns a numpy array of x coordinate values.

Returns:

x: numpy.ndarray

The values of x coordinate.

y

Read-only property

Returns a numpy array of y coordinate values.

Returns:

y: numpy.ndarray

The values of y coordinate.

z

Read-only property

Returns a numpy array of z coordinate values.

Returns:

z: numpy.ndarray

The values of z coordinate.

intensity

Read-only property

Returns a numpy array of intensity values.

Returns:

intensity: numpy.ndarray

The values of intensity.

red

Read-only property

Returns a numpy array of red values.

Returns:

red: numpy.ndarray

The values of red.

green

Read-only property

Returns a numpy array of green values.

Returns:

green: numpy.ndarray

The values of green.

blue

Read-only property

Returns a numpy array of blue values.

Returns:

blue: numpy.ndarray

The values of blue.

classification

Read-only property

Returns a numpy array of classification values.

Returns:

classification: numpy.ndarray

The values of classification.


Available special methods:

__len__()

Returns the number of points in the chunk.

Returns:

length: int

The number of points.

__repr__()

Returns the string representation of the chunk.

Returns:

repr: str

String representation.

class PointCloudChunkIterator

Available special methods:

__iter__()

Returns self.

Returns:

self: ecognition.PointCloudChunkIterator

Returns self.

__next__()

Returns the next point cloud chunk

Returns:

chunk: ecognition.PointCloudChunk

The point cloud chunk.

class PointCloud

Available methods:

get_chunk_iterator(points_in_chunk=1000000)

Creates a chunk iterator, capable of iterating over the point cloud points. Only one PointCloudChunkIterator may exist at one time.

Parameters:

points_in_chunk: int

The number of points in a point cloud chunk.

Returns:

chunk_iterator: ecognition.PointCloudChunkIterator

The point cloud chunk iterator.

Raises:

ValueError

if point cloud is not closed, or an instance of PointCloudChunkIterator already exists.

add_points(x, y, z, intensity, red, green, blue, classification)

Adds point cloud points to the PointCloud object. Each field array must have the same size. Values of the same index correspond to the same point.

Parameters:

x: numpy.ndarray

Numpy array containing point cloud X coordinates.

y: numpy.ndarray

Numpy array containing point cloud Y coordinates.

z: numpy.ndarray

Numpy array containing point cloud Z coordinates.

intensity: numpy.ndarray

Numpy array containing point cloud intensity values.

red: numpy.ndarray

Numpy array containing point cloud red values.

green: numpy.ndarray

Numpy array containing point cloud green values.

blue: numpy.ndarray

Numpy array containing point cloud blue values.

classification: numpy.ndarray

Numpy array containing point cloud classification.

Raises:

ValueError

If closed.

If arguments have an unsupported data type, the number of dimensions is not equal to 1, or arguments element count is not equal.

get_point_count()

Returns the number of points in the PointCloud.

Returns:

point_count: int

The number of points.

close()

Finalizes PointCloud object. Must be called for new PointCloud objects created with ecognition.PointCloud.create_point_cloud method.

Raises:

ValueError

If the point cloud is already closed.


Available static methods

create_point_cloud(name)

Static method

Creates an empty point cloud, with the given name. If the point cloud with the specified name already exists, it is deleted, before a new one is created.

Parameters:

name: str

Name of the point cloud.

Returns:

point_cloud: ecognition.PointCloud

The created point cloud.

Functions

set_variable(name, value)

Sets an eCognition variable. If it does not exist, it is created.

Parameters:

name: str

The name of the variable.

value: int, float or str

The value to set the variable to.

Raises:

ValueError

If value type is unsupported.

set_array(name, values)

Fills an eCognition array with the given values. If an array does not exist, it is created. All elements of the values sequence must have the same type.

Parameters:

name: str

The name of the array.

values: sequence of int, float or str

The values to fill the array with.

Raises:

ValueError

If value type is unsupported. Or sequence elements are not of the same type.

set_region(name, region)

Sets an eCognition region. If a region does not exist, it is created. The region array must have a specific shape:

2D region

numpy.ndarray shape - [2, 2]

data - [[x_pos, y_pos], [x_size, y_size]]

3D region

numpy.ndarray shape - [2, 3]

data - [[x_pos, y_pos, z_pos], [x_size, y_size, z_size]]

4D region

numpy.ndarray shape - [2, 4]

data - [[x_pos, y_pos, z_pos, t_pos], [x_size, y_size, z_size, t_size]]

Time series region

numpy.ndarray shape - [2, 4]

data - [[x_pos, y_pos, 0, t_pos], [x_size, y_size, 0, t_size]]

(for time series region z_pos and z_size must be equal to 0)

x_pos, y_pos, z_pos, and t_pos are the starting point of a region.

x_size, y_size, z_size, and t_size are the extent of a region.


Parameters:

name: str

The name of the region.

region: numpy.ndarray

The numpy array containing region.

Raises:

ValueError

If the region is of incorrect type or shape.

 

wait_for_debugger(host=”localhost”, port=5678)

Blocks code execution and waits for a debugger to connect. Listens on a specified host and port. Debugger is implemented using a debugpy package: “https://github.com/microsoft/debugpy”, so it is possible to attach to the eCognition process and debug python code using tools that support debugpy.

Please refer to User Guide > Python Integration >Debugging python code in eCognition Developer for details.

Parameters:

host: str

The host to listen for the debugger on.

port: int

The port to listen for the debugger on.

Raises:

ValueError

If the host or port has been changed after the debug session has already been created.

RuntimeError

If this function is called on Linux (only Windows is supported).

If debugpy package is not installed in the active environment.

write_message(message, show_message_box=False)

Writes a message to the eCognition log file. It also shows up in the View -> Message Console window. If show_message_box is True, then in addition, an information window box shows up with the message. Script execution is blocked until the message box is closed.

Parameters:

message: str

The message to write.

show_message_box: bool

Whether to show a message box.

Hints

Hint 1 - Printing from python script

Because the console window is disabled in eCognition Developer, Pythons standard output to stdout is not visible. This hint lists some alternatives, in case you need to print some debug information during the development of your script.

 

 

The simplest way to print a message from python is to use a ecognition.write_message function:

import ecognition as ecog

def print_message(input_dict):
  print_string = "Use write_message function"
  ecog.write_message(print_string, True)

 

Another way to print debug messages would be to use an external log file (a dedicated logging package is recommended for this approach). For example:

def log_to_file(input_dict):
  log_file = input_dict["variable"]["var_log_file"]

  with open(log_file, "a") as file:
    file.write("log entry 1\n")
    file.write("log entry 2\n")

Additionally you can log all contents to an external file. For example:

def log_to_file(input_dict):
  log_file = input_dict["variable"]["var_log_file"]

  with open(log_file, "a") as file:
    file.write("log entry 1\n")
    file.write("log entry 2\n")


Hint 2 - Using external python files in inline script

If you need to import an external file into a python script, the script must be enabled to find that external file. That is done by adding the location of the external file into the process parameter “External script paths”. For example, for the following script:


C:\scripts\ExternalFile.py

import ecognition as ecog

def set_variable():
  ecog.set_variable("var_from_ext_file", "Set from external file.")


And this inline python script:



from ExternalFile import set_variable

def use_external_file(input_dict):
  set_variable()

Important - the parameter “External scripts path” must be defined as an array that contains “C:\scripts” as string value.